package com.warrior.gatherserver.runner;

import com.warrior.gatherserver.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClassName com.warrior.common.tag.runner.CreateEsIndexRunner.java
 * @Author xujian
 * @Description 初始化创建索引
 * @CreateTime 2020年09月23日 14:38:00
 */
@Component
@Slf4j
public class CreateEsIndexRunner implements CommandLineRunner {

    @Autowired
    private MessageService messageService;

    /**
     * @Description 默认标签表创建的mapping
     **/
    private final static String ES_MAPPING_TEMPLATE =
            "{" +
                 "\"dynamic_templates\" : [" +
                    "{" +
                    "\"strings\" : {" +
                        "\"match_mapping_type\" : \"string\", " +
                            "\"mapping\" : {" +
                                     "\"type\" : \"keyword\"" +
                                "}" +
                        " }" +
                        "}" +
                    " ]," +
                    "\"properties\":{" +
                            "\"ip\":{\"type\":\"keyword\"}," +
                            "\"metricName\":{\"type\":\"keyword\"}," +
                            "\"createTimeStr\":{\"type\":\"keyword\"}," +
                            "\"createTime\":{\"type\":\"date\",\"format\" : \"yyyy-MM-dd HH:mm:ss\"}," +
                            "\"metrics\" : {" +
                                "\"properties\" : { \"metricName\" : {  \"type\" : \"keyword\"}," +
                                                 "\"metricValue\" : { \"type\" : \"keyword\"" + "}" +
                                         "}" +
                             "}"+
                    "}" +
             "}";

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Value("${spring.elasticsearch.gather-index}")
    private String gatherIndex;

    @Override
    public void run(String... args) {
        try {
            messageService.getProperties();
            boolean indexFlag = restTemplate.indexExists(gatherIndex);
            if (!indexFlag) {
                log.info("============ {} 索引新建成功 ==========", gatherIndex);
                restTemplate.createIndex(gatherIndex);
                restTemplate.putMapping(gatherIndex, "_doc", ES_MAPPING_TEMPLATE);
            }
        } catch (Exception e) {
            log.error("=========== 初始化es索引检测异常 msg: {} ===========", e.getMessage());
        }
    }

}
